/*
 * ImageCache.cpp
 *
 *  Created on: 20/10/2009
 *      Author: marcos
 */

#include "ImageCache.h"

namespace gui {

ImageCache::ImageCache() {
	this->hash = new util::HashMap<std::string, SDL_Surface>();
}

ImageCache::~ImageCache() {
	util::LinkedList<std::string>::Iterator it = this->hash->keySet()->iterator();
	while (it.hasNext()) {
		this->freeImage(*it.next());
	}
	delete this->hash;
}

SDL_Surface* ImageCache::getImage(std::string filename) {
	if (this->hash->containsKey(&filename)){
		if (this->hash->get(&filename) != NULL) {
			return this->hash->get(&filename);
		}
	}
	SDL_Surface* image = this->loadImage(&filename);
	this->hash->put(new std::string(filename), image);
	return image;
}

void ImageCache::freeImage(std::string filename) {
	SDL_Surface* surface = this->hash->remove(&filename);
	SDL_FreeSurface(surface);
}

SDL_Surface* ImageCache::loadImage(std::string* filename) {
	SDL_Surface* tempImage = NULL;
	SDL_Surface* optimizedImage = NULL;

	tempImage = SDL_LoadBMP(filename->c_str());
	optimizedImage = SDL_DisplayFormat(tempImage);
	SDL_FreeSurface(tempImage);

	SDL_SetColorKey(optimizedImage,SDL_SRCCOLORKEY,
			SDL_MapRGB(optimizedImage->format,255,0,255));

	return optimizedImage;
};

} // end of namespace
